﻿using AutoMapper;
using MediatR;
using Management.API.Application.Controller.Management;
using Management.Domain;
using Management.Errorcode;
using Management.Errorcode.ErrorCode;
using Management.Infrastructure.Interfaces;
using Management.Infrastructure.Interfaces.BOMManagement;
using Management.Models.BOMBasicInformation;
using Management.API.Application.Controller.Management.Product;

namespace Management.API.Application.CommandHandler
{
    public class AddProductCommandHandler : IRequestHandler<AddProductCommand, ApiResult>
    {
        private readonly IProductRepository _iProductRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddProductCommandHandler> _logger;

        public AddProductCommandHandler(IProductRepository IProductRepository, IMapper mapper, ILogger<AddProductCommandHandler> logger)
        {
            _iProductRepository = IProductRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult> Handle(AddProductCommand request, CancellationToken cancellationToken)
        {

            try
            {
                // 将 DTO 映射为实体类 Product
                var userEntity = _mapper.Map<Product>(request);

                // 调用仓储层添加BOM
                var addedUser = await _iProductRepository.InsertAsync(userEntity);

                // 返回成功结果
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加产品失败");
                return ApiResult.Fail("添加产品失败", StatusCodeEnum.InternalServerError);
            }
        }

    }
}
